package cn.jluzh.blog.modules.user.service.impl;

import cn.jluzh.blog.commons.utils.FileUtil;
import cn.jluzh.blog.mapper.SysUserMapper;
import cn.jluzh.blog.modules.security.eneity.SecurityUser;
import cn.jluzh.blog.modules.user.entity.FileProperties;
import cn.jluzh.blog.modules.user.entity.SysUser;
import cn.jluzh.blog.modules.user.service.UploadService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author hzhii
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FileProperties properties;

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
     public Map<String, String> updateAvatar(MultipartFile multipartFile) {
        SysUser user = SecurityUser.getUser();
        String oldPath = user.getAvatarUrl();
        File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
        user.setAvatarUrl(Objects.requireNonNull(file).getPath());
        user.setAvatarName(file.getName());
        sysUserMapper.updateById(user);
        if (StringUtils.isNotBlank(oldPath)) {
            FileUtil.del(oldPath);
        }
        return new HashMap<String, String>(1) {{
            put("avatar", file.getName());
        }};
    }

    @Override
    public String updateImage(MultipartFile multipartFile) {
        File file = FileUtil.upload(multipartFile, properties.getPath().getImage());
        return file.getName();
    }
}
